/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ANIUTIL_SCOPE_H
#define ANIUTIL_SCOPE_H

#include <ani.h>

#include "base.h"

namespace OHOS {
namespace AniUtil {

class LocalScopeGuard {
public:
    LocalScopeGuard(ani_env *env, size_t nrRefs) : env_(env)
    {
        status_ = env_->CreateLocalScope(nrRefs);
    }

    ~LocalScopeGuard()
    {
        if (ANI_OK != status_) {
            return;
        }
        env_->DestroyLocalScope();
    }

    bool IsStatusOK()
    {
        return ANI_OK == status_;
    }

    ani_status GetStatus()
    {
        return status_;
    }

private:
    ani_env *env_ = nullptr;
    ani_status status_ = ANI_ERROR;
};


class ScopedEnv {
public:
    static expected<std::unique_ptr<ScopedEnv>, ani_status> Create(ani_vm* vm)
    {
        ani_env *env = nullptr;
        ani_options aniArgs {0, nullptr};
        auto status = vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env);
        if (ANI_OK != status) {
            status = vm->GetEnv(ANI_VERSION_1, &env);
            if (ANI_OK != status) {
                return status;
            }
        }
        auto ptr = new ScopedEnv(vm, env);
        return std::unique_ptr<ScopedEnv>(ptr);
    }

    static expected<std::unique_ptr<ScopedEnv>, ani_status> Create(ani_env* env)
    {
        ani_vm *vm = nullptr;
        auto status = env->GetVM(&vm);
        if (ANI_OK != status) {
            return status;
        }
        return Create(vm);
    }

    ~ScopedEnv()
    {
        if (vm_) {
            vm_->DetachCurrentThread();
            vm_ = nullptr;
        }
        env_ = nullptr;
    }

    ani_env *GetEnv()
    {
        return env_;
    }

    ScopedEnv(const ScopedEnv&) = delete;
    ScopedEnv& operator=(const ScopedEnv&) = delete;

private:
    ScopedEnv(ani_vm* vm, ani_env* env) : vm_(vm), env_(env)
    {
    }

private:
    ani_vm *vm_ = nullptr;
    ani_env* env_ = nullptr;
};

} // namespace AniUtil
} // namespace OHOS

#endif
